from lviewer.util import console

class NoToolError( Exception ):
    pass

class PathTool( object ):
    def __init__(self, name):
        self.name = name

    def __call__(self):
        # we need to find out if the given file can be located
        try:
            result = console.execute([self.name])
        except OSError:
            return None # we didn't find one

        try:
            result.finish()
        except console.ToolFailure:
            pass # if the tool didn't like it, we're still fine

        return (self.name, Tool.Priorities.Standard)



class Tool(object):
    class Priorities:
        AlwaysBest = 0
        PrettyGood = 100
        Standard = 200
        LastResort = 300

    
    def __init__(self, name, check_path = False):
        self.sources = []
        self.name = name

        if check_path:
            self.add_source( PathTool(self.name) )

    def add_source(self, fn):
        self.sources.append(fn)

    @property
    def path(self):
        sources = [fn() for fn in self.sources]
        sources = [x for x in sources if x]
        if not sources:
            raise NoToolError(self.name)
        sources.sort(key = lambda x: x[1])
        return sources[0][0]


    def __str__(self):
        return self.path
